<template>
  <el-dialog
    v-model="dialogVisible"
    :title="village.villageId ? '修改乡村信息' : '新增乡村信息'"
    width="500"
    @submit.prevent
  >
    <el-form>
      <el-form-item label="乡村名称">
        <el-input v-model="villageName" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="VillageDialog">
import { addVillage, updateVillage } from '@/api/village'
import useErrorMessage from '@/hooks/useErrorMessage'
import { ElMessage } from 'element-plus'

const mProps = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  village: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:visible', 'refresh'])
const villageName = ref<string>(mProps.village.villageName || '')

const dialogVisible = computed({
  get() {
    return mProps.visible
  },
  set(value) {
    emit('update:visible', value)
  }
})

const handleSubmit = async () => {
  const name = villageName.value.trim()
  if (!name) {
    ElMessage.warning('请输入乡村名称')
    return
  }
  try {
    if (mProps.village.villageId) {
      // 修改
      await updateVillage({
        villageId: mProps.village.villageId,
        villageName: name
      })
      ElMessage.success('修改成功')
    } else {
      // 新增
      await addVillage({ villageName: name })
      ElMessage.success('添加成功')
    }
    emit('refresh')
    dialogVisible.value = false
  } catch (error) {
    useErrorMessage(error)
  }
}
</script>

<style lang="scss" scoped></style>
